<template>
  <div>
    <!-- 求购 -->
    <div
      :style="{
        position: 'relative'
      }"
    >
      <FormPanel ref="sparePartsPurchase" :list="formList" :cols="3" labelWidth="120" formType="add" @formChange="sparePartsInfoChange" />
    </div>

    <!-- 发布弹窗 -->
    <div>
      <BaseDialog :visible.sync="visible" destroyOnClose :title="dialogTitle" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <PromptInfoPurchase :infoType="infoType" :partsName="partsName" :promptArray="promptArray" :saveInfo="saveData" :partNo="partNo" @close="closePrompt" />
      </BaseDialog>
      <!-- 配件搜索帮助 -->
      <BaseDialog :visible.sync="partVisible" :title="'配件搜索帮助'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <PartInfoSearch :mode="'single'" :storageParams="storageParams" @close="closeSearchDialog" @onConfirm="confirmHandle" />
      </BaseDialog>
    </div>
  </div>
</template>

<script>
import PromptInfoPurchase from './promptInfoPurchase';
import { saveInfo, getInfo, getOrgByOrgType, detail, findOne, getChildOrgByOrgId } from '@/api/part/exchange/platform';
import PartSelect from '@/pages/part/partPurchase/purchaseOrder/partSelect';
import salesOrderAdd from './salesOrderAdd';
import PartInfoSearch from './partInfoSearch';
import { jsonToHump } from '@/utils/index';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import { queryTex, queryDefaultDealer, getStorageList } from '@/api/part/common';
export default {
  name: 'Purchase',
  components: { PromptInfoPurchase, PartSelect, PartInfoSearch },
  mixins: [dictionary],
  props: {
    type: {
      type: String,
      default: 'add'
    },
    rowData: {
      type: Object,
      default: () => ({})
    },
    params: {
      type: Object
    },
    tax: {
      type: Number
    }
  },
  data() {
    // 表单保存数据
    this.saveData = {};
    return {
      formList: this.createSaleFormList(),
      visible: false,
      partVisible: false,
      dialogTitle: '',
      infoType: '求购',
      partsName: '',
      promptArray: ['出售', '扳手', '求购'],
      // 配件代码
      partNo: '',
      // 仓库列表
      storageList: [],
      provienceList: [],
      cityList: [],
      countryList: [],
      // 销售类型
      saleType: 97011002,
      // 可用数量(用于校验)
      useableQuantity: 0,
      taxRate: 0,
      partPlatformId: null,
      defaultDealer: '', // 默认经销商
      storageParams: '' // 仓库字符串->oem
    };
  },
  created() {
    // this.getDictList();
    this.provienceList = this.createDictRegion();
    this.getOrgType();
    this.getDefaultDealer();
    this.getControlledStorage();
  },
  methods: {
    async getControlledStorage() {
      let res = await getStorageList();
      let arr = [];
      if (res.data.length) {
        res.data.forEach(x => {
          if (x.OEM_TAG == '10451002') {
            arr.push(x.STORAGE_CODE);
          }
        });
      }
      this.storageParams = arr.join("','");
      console.log(this.storageParams, '仓库');
    },
    // 不含税计算
    excludeTaxCalculate(val) {
      return eval(val / (1 + this.tax));
    },
    // 获取默认经销商
    async getDefaultDealer() {
      let res = await queryDefaultDealer();
      this.defaultDealer = res.data;
      this.formList.forEach(element => {
        if (element.fieldName == 'dealer') {
          element.initialValue = this.defaultDealer;
        }
      });
    },
    // 获取大区列表
    async getOrgType() {
      try {
        let res = await getOrgByOrgType({ orgType: 15061006, companyId: 1 });
        // console.log(res);
        if (res.resultCode == 200) {
          this.formList.find(item => item.fieldName == 'regionCode').itemList = res.data.map(e => ({ text: e.orgName, value: e.orgId }));
        }
      } catch (error) {
        this.$notify.error({ title: '提示信息', message: '获取经销商大区列表失败' });
      }
    },
    // 选择大区后 小区
    async regionSelect(val) {
      let res = await getChildOrgByOrgId({ orgCode: val });
      // console.log('小区', res);
      this.formList.find(item => item.fieldName == 'areaCode').itemList = res.data.map(x => ({ text: x.orgName, value: x.orgCode }));
    },
    // 配件弹窗确认按钮
    confirmHandle(val) {
      console.log(1231, val);
      // 查询是否重复
      this.releasedInfo(val);
      this.formList.find(item => item.fieldName == 'partNo').initialValue = val[0].partNo;
      this.formList.find(item => item.fieldName == 'storageCode').itemList = [{ text: val[0].storageName, value: val[0].storageCode }];
      this.formList.find(item => item.fieldName == 'storageCode').initialValue = val[0].storageCode;
      this.formList.find(item => item.fieldName == 'partName').initialValue = val[0].partName;
      this.formList.find(item => item.fieldName == 'stockQuantity').initialValue = val[0].stockQuantity; // 库存
      this.formList.find(item => item.fieldName == 'useableQuantity').initialValue = val[0].useableQuantity; // 可用库存
      this.formList.find(item => item.fieldName == 'shortQuantity').initialValue = val[0].shortQuantity; // 欠料
      this.formList.find(item => item.fieldName == 'costOutPrice').initialValue = val[0].costOutPrice; // 含税出库单价
      this.formList.find(item => item.fieldName == 'costSalesPrice').initialValue = val[0].costSalesPrice; // 含税销售单价
      this.formList.find(item => item.fieldName == 'costPrice').initialValue = val[0].costPrice; // 不含税成本单价
      this.formList.find(item => item.fieldName == 'costAmount').initialValue = val[0].stockQuantity * val[0].costPrice; // 不含税成本金额
      this.formList.find(item => item.fieldName == 'planPrice').initialValue = val[0].planPrice * (1 + this.tax); // 含税采购单价
      this.formList.find(item => item.fieldName == 'inOutTaxedPrice').initialValue = val[0].costSalesPrice; // 默认求购单价=含税销售价格

      this.closeSearchDialog();
    },
    // 查询是否有发布信息
    async releasedInfo(val) {
      let res = await findOne({ partNo: val[0].partNo, storageCode: val[0].storageCode, saleType: this.saleType });
      // console.log('是否发布', res);
      if (res.resultCode == 200) {
        if (res.data.getOwnPropertyNames().length != 0 && res.data.partPlatformId != null) {
          this.partPlatformId = res.data.partPlatformId;
          return this.$notify.success({ title: '提示信息', message: '您选择的配件在平台上已有发布信息' });
        }
      }
    },
    // 关闭配件弹窗
    closeSearchDialog() {
      this.partVisible = false;
    },
    // 配件数据
    changedata(val) {
      this.closePart();
      let partInformation = val;
      jsonToHump(partInformation);
      // console.log('配件信息', partInformation);
      this.createFormData(val);
    },

    // 关闭配件弹窗
    closePart() {
      this.partVisible = false;
    },
    async getDictList() {
      let res = await getStorageList({ currentPage: 1, pageSize: 20 });
      this.storageList = res.data;
      console.log(this.storageList);

      this.formList.find(item => item.fieldName == 'storageCode').itemList = this.storageList.map(e => ({ text: e.storageName, value: e.storageCode }));
    },
    // 获取到期日期
    // 关闭消息提示
    closePrompt(val, type) {
      this.visible = val;
      console.log(type);
      if (type === 'refresh') {
        this.closeDialog(type);
      }
    },
    // 关闭按钮事件
    closeDialog(type) {
      this.$emit('closeEvent', type, this.saleType);
    },
    // 配件代码搜索
    searchPartsHandle() {
      this.partVisible = true;
    },
    // 表单信息改变触发
    async sparePartsInfoChange(val) {
      //
      this.saveData = { ...val, saleType: this.saleType };
      // console.log('表单数据', this.saveData);
      this.dialogTitle = '发布配件求购信息提醒';
      this.partsName = this.saveData.partsName;
      this.partNo = this.saveData.partNo;
      this.visible = true;
    },
    // 创建出售配件信息
    createSaleFormList() {
      return [
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          placeholder: '',
          rules: [{ required: true, message: '请选择...', trigger: 'blur' }],
          readonly: true,
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.searchPartsHandle}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          placeholder: '请输入...',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          placeholder: '',
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '欠料数量',
          fieldName: 'shortQuantity',
          placeholder: '',
          precision: 2,
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '库存数量',
          fieldName: 'stockQuantity',
          placeholder: '',
          precision: 2,
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '可用数量',
          fieldName: 'useableQuantity',
          placeholder: '',
          precision: 2,
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '含税出库单价',
          fieldName: 'costOutPrice',
          placeholder: '',
          precision: 2,
          disabled: true

          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '含税销售单价',
          fieldName: 'costSalesPrice',
          placeholder: '',
          precision: 2,
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '含税批发单价',
          fieldName: 'costWholesalesPrice', // 不含税
          placeholder: '',
          precision: 2,
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '不含税成本单价',
          fieldName: 'costPrice', // 查出来含税
          placeholder: '',
          precision: 2,
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '不含税成本金额',
          fieldName: 'costAmount',
          placeholder: '',
          precision: 2,
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'INPUT_NUMBER',
          label: '含税采购单价',
          fieldName: 'planPrice',
          placeholder: '',
          precision: 2,
          disabled: true
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // readonly: true
        },
        {
          type: 'SELECT',
          label: '快递方式',
          fieldName: 'expressType',
          // rules: [{ required: true, message: '请先维护工时定额', trigger: 'blur' }],
          // 快递到付，快递包邮，自取，其他
          itemList: this.createDictList('8114')
        },
        {
          type: 'INPUT_NUMBER',
          label: '含税求购单价',
          fieldName: 'inOutTaxedPrice',
          // 含税出售单价=不含税成本单价*（1+税率）* H，0<H<=1+M
          placeholder: '',
          precision: 2,
          rules: [{ required: true, message: '请输入含税求购单价', trigger: 'blur' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '求购数量',
          fieldName: 'quantity',
          min: 0.01,
          placeholder: '',
          precision: 2,
          rules: [
            { required: true, message: '请输入求购数量', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                if (value > 0) {
                  callback();
                } else {
                  callback(new Error('求购数量不能为0'));
                }
              },
              trigger: ['blur', 'change']
            }
          ]
        },
        {
          type: 'DATE',
          label: '到期日期',
          fieldName: 'endDate',
          placeholder: '',
          initialValue: moment()
            .add('days', 3)
            .format('YYYY-MM-DD HH:mm:ss'),
          // 当前日期+三天
          rules: [{ required: true, message: '请选择到期日期', trigger: 'blur' }]
        },
        {
          type: 'CHECKBOX',
          label: '可见范围',
          fieldName: 'isShow',
          placeholder: '',
          initialValue: '10041002',
          options: { trueValue: '10041001', falseValue: '10041002' },
          offsetRightCols: 2
        },
        {
          type: 'SELECT',
          label: '大区',
          fieldName: 'regionCode',
          placeholder: '',
          itemList: [],
          change: props => {
            this.regionSelect(props);
          }
        },
        {
          type: 'SELECT',
          label: '小区',
          fieldName: 'areaCode',
          placeholder: '',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'proCode',
          placeholder: '',
          itemList: this.createDictRegion(),
          change: props => {
            this.formList.find(item => item.fieldName == 'city').itemList = this.provienceList.find(item => item.value == props).children;
          }
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'city',
          placeholder: '',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '经销商', // 没有字段
          fieldName: 'dealer',
          placeholder: ''
        }
      ];
    }
  }
};
</script>

<style></style>
